#include <stdio.h>
#include "simpleXML.h"


void simpleXML::getStatement(FILE* fp)
{
	char ch;
	//find '<'
	do {
		ch = fgetc(fp);
	} while (ch != '<' && ch != EOF && ch != '\n');
	if (ch == '\n' || ch == EOF)
	{
		throw("failed to load file");
	}

	//find '?'
	ch = fgetc(fp);
	if (ch != '?' || ch == '\n' || ch == EOF)
	{
		fclose(fp);
		throw("failed to load file");
	}

	//find "xml"
	ch = fgetc(fp);
	if (ch != 'x' || ch == '\n' || ch == EOF)
	{
		fclose(fp);
		throw("failed to load file");
	}
	ch = fgetc(fp);
	if (ch != 'm' || ch == '\n' || ch == EOF)
	{
		fclose(fp);
		throw("failed to load file");
	}
	ch = fgetc(fp);
	if (ch != 'l' || ch == '\n' || ch == EOF)
	{
		fclose(fp);
		throw("failed to load file");
	}
	xml.elementName = "xml";

	//find the first necessary blank character
	ch = fgetc(fp);
	if(ch != '\t' && ch != ' ')
	{
		fclose(fp);
		throw("failed to load file");
	}
	do//find and escape every blank character, '\t' or ' ', if exists
	{
		ch = fgetc(fp);
	} while (ch == ' ' || ch == '\t');

	if (65 > ch || ch > 122 || (ch > 90 && ch < 97))//first must be a letter
	{
		throw ("wrong name");
	}
	
	//get every properties of statement
	do
	{
		do
		{
			(xml.properties)->name += ch;
			ch = fgetc(fp);

		} while (ch != ' ');
		
	} while (ch != '?' && ch != '\n' && ch != EOF);
	if (ch == '\n' || ch == EOF)
	{
		throw("failed to load file");
	}

	//now ch equals to '?'
	ch = fgetc(fp);//read next character after '?'
	if (ch != '>')
	{
		throw("failed to load file");
	}

}

simpleXML::simpleXML(char* path)
{
	FILE* fp;
	char ch;
	if ((fp = fopen(path, "rt")) == NULL)
	{
		throw("Cannot open file strike any key exit!");
	}
	getStatement(fp);
	ch = fgetc(fp);
	int parenth_left = 0;
	int parenth_right = 0;
	while (ch != EOF)
	{
		if (ch == '<')
		{
			++parenth_left;
		}
		if (ch == '>')
		{

		}
		ch = fgetc(fp);
	}
	fclose(fp);
}

simpleXML::~simpleXML()
{
}
void simpleXML::saveXML(char * path)
{
}
//
//simpleXML && simpleXML::load_file(const string &)
//{
//	return simpleXML && ();
//}
//
//elemt * simpleXML::add_child(elemt * parent, elemt * child)
//{
//	return nullptr;
//}
//
//elemt * simpleXML::remove_child(elemt * parent, unsigned int nth)
//{
//	return nullptr;
//}
//
//elemt * simpleXML::remove_all_children(elemt * parent)
//{
//	return nullptr;
//}
//
//void simpleXML::echo()
//{
//}
//
//void simpleXML::saveXML(ifstream & ifs)
//{
//}
//
//void simpleXML::saveXML(string && path)
//{
//}
